﻿#include "mainwindow.h"
#include "FlowView.h"
#include "SVGUtils.h"
#include <QVBoxLayout>
#include <QToolButton>
#include <QMessageBox>
#include <QPushButton>
#include <QSpinBox>
#include <QLabel>
#include <QPropertyAnimation>
#include <QApplication>
#include <QFontComboBox>
#include <QWidgetAction>
#include <QDebug>
#include <QFontComboBox>
#include <QFont>
#include <QFileDialog>
#include <QTimer>



MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
{
    // 设置窗口属性
    setWindowTitle(tr("Flow Chart"));
    setWindowIcon(QIcon(":/icons/flowchart.png"));
    resize(1500, 1050);
    m_model = &ShapeManager::instance();
    // 核心区域初始化
    initCentralWidget();        // 必须先设置中央部件
    initFunctionToolArea();  // 功能区选项卡
    initShapeLibraryDock();     // 左侧图形库
    initPropertyDock();         // 右侧属性面板
    initStatusBar(); //状态栏
}

MainWindow::~MainWindow()
{
}

void MainWindow::initCentralWidget() {
    // 创建绘图视图（核心区域）
    // 创建视图（包含滚动区域）
    m_flowChartWidget = new FlowChartWidget(this);
    // 设置主窗口中心部件
    setCentralWidget(m_flowChartWidget);
}


void MainWindow::initShapeLibraryDock()
{
    // 1. 创建内容面板
    m_shapeLibraryPanel = new ShapeLibraryPanel();
    m_shapeLibraryPanel->setMinimumWidth(300); // 设置展开时的最小宽度
    m_shapeLibraryPanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    // 2. 创建折叠/展开按钮
    m_toggleShapeLibBtn = new QToolButton();
    m_toggleShapeLibBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
    m_toggleShapeLibBtn->setObjectName("toggleShapeLibBtn");
    m_toggleShapeLibBtn->setCheckable(true);
    m_toggleShapeLibBtn->setChecked(true); // 初始为收拢状态
    m_toggleShapeLibBtn->setArrowType(Qt::LeftArrow); // > 箭头
    m_toggleShapeLibBtn->setFixedSize(20, 60); // 竖排长按钮


    // 3. 创建容器 Widget 来放置面板和按钮
    QWidget* container = new QWidget();
    QHBoxLayout* containerLayout = new QHBoxLayout(container);
    containerLayout->setContentsMargins(0, 0, 0, 0);
    containerLayout->setSpacing(0);
    containerLayout->addWidget(m_shapeLibraryPanel,1);
    containerLayout->addWidget(m_toggleShapeLibBtn);

    // 4. 创建 DockWidget
    QDockWidget* dock = new QDockWidget(tr("Shape"), this);
    dock->setObjectName("shapeLibraryDock");
    dock->setWidget(container);
    dock->setFeatures(QDockWidget::NoDockWidgetFeatures); // 禁用所有特性
    dock->setTitleBarWidget(new QWidget()); // 隐藏标题栏
    addDockWidget(Qt::LeftDockWidgetArea, dock);

    // 6. 连接按钮点击事件
    connect(m_toggleShapeLibBtn, &QToolButton::toggled, [=](bool expanded) {
        m_toggleShapeLibBtn->setArrowType(expanded ? Qt::LeftArrow : Qt::RightArrow);
        m_shapeLibraryPanel->setVisible(expanded);
        });
}


void MainWindow::initPropertyDock()
{
    // 1. 创建内容面板
    m_propertyEditorWidget = new PropertyEditorWidget();
    m_propertyEditorWidget->setMinimumWidth(300); // 设置展开时的最小宽度
    m_propertyEditorWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 2. 创建折叠/展开按钮
    QToolButton* m_toggleShapeLibBtn = new QToolButton();
    m_toggleShapeLibBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    m_toggleShapeLibBtn->setObjectName("toggleShapeLibBtn");
    m_toggleShapeLibBtn->setCheckable(true);
    m_toggleShapeLibBtn->setChecked(true); // 初始为收拢状态
    m_toggleShapeLibBtn->setArrowType(Qt::RightArrow); // > 箭头
    m_toggleShapeLibBtn->setFixedSize(20, 60); // 竖排长按钮
   

    // 3. 创建容器 Widget 来放置面板和按钮
    QWidget* container = new QWidget();
    QHBoxLayout* containerLayout = new QHBoxLayout(container);
    containerLayout->setContentsMargins(0, 0, 0, 0);
    containerLayout->setSpacing(0);
    containerLayout->addWidget(m_toggleShapeLibBtn);
    containerLayout->addWidget(m_propertyEditorWidget);

    // 4. 创建 DockWidget
    QDockWidget* dock = new QDockWidget(tr("Shape"), this);
    dock->setObjectName("shapeLibraryDock");
    dock->setWidget(container);
    dock->setFeatures(QDockWidget::NoDockWidgetFeatures); // 禁用所有特性
    dock->setTitleBarWidget(new QWidget()); // 隐藏标题栏
    addDockWidget(Qt::RightDockWidgetArea, dock);


    // 6. 连接按钮点击事件
    connect(m_toggleShapeLibBtn, &QToolButton::toggled, [=](bool expanded) {
        m_toggleShapeLibBtn->setArrowType(expanded ? Qt::RightArrow : Qt::LeftArrow);
        m_propertyEditorWidget->setVisible(expanded);
        });
}


void MainWindow::initFunctionToolArea() {
    // 创建选项卡栏（放在主工具栏区域）
    m_functionTabBar = new QTabBar(this);
    // 设置选项卡属性
    m_functionTabBar->setShape(QTabBar::RoundedNorth);
    m_functionTabBar->setExpanding(false);  // 关键！禁止自动扩展
    m_functionTabBar->setUsesScrollButtons(false); // 禁用滚动按钮


    // 创建堆叠式工具栏
    m_functionToolStack = new QStackedWidget(this);

    // 添加功能区页面
    m_functionTabBar->addTab(tr("File"));
    m_functionToolStack->addWidget(createFileToolPage());

    m_functionTabBar->addTab(tr("Start"));
    m_functionToolStack->addWidget(createHomeToolPage());

    m_functionTabBar->addTab(tr("Arrange"));
    m_functionToolStack->addWidget(createArrangeToolPage());

    m_functionTabBar->addTab(tr("Page"));
    m_functionToolStack->addWidget(createPageLayoutPage());

    // 将选项卡和工具栏组合到容器中
    QWidget* toolContainer = new QWidget();
    QVBoxLayout* toolLayout = new QVBoxLayout(toolContainer);
    toolLayout->setSpacing(0);
    toolLayout->setContentsMargins(0, 0, 0, 0);

    toolLayout->addWidget(m_functionTabBar);
    toolLayout->addWidget(m_functionToolStack);

    // 作为独立工具栏添加到顶部
    QToolBar* functionToolBar = new QToolBar("Function", this);
    functionToolBar->addWidget(toolContainer);
    functionToolBar->setMovable(false);  // 固定位置
    addToolBar(Qt::TopToolBarArea, functionToolBar);

    // 连接信号
    connect(m_functionTabBar, &QTabBar::currentChanged,
        m_functionToolStack, &QStackedWidget::setCurrentIndex);
}

void MainWindow::initStatusBar()
{
    statusBar()->showMessage(tr("Ready"));
}


//滑动工具栏
QWidget* MainWindow::createFileToolPage() {
    QWidget* page = new QWidget();
    QToolBar* toolBar = new QToolBar(page);  // 工具栏名称（可选）
    //toolBar->setIconSize(QSize(32, 32));

    // 1. 新建按钮
    QAction* newAction = new QAction(QIcon(":/icons/note_add.png"), tr("New"), this);
    newAction->setShortcut(QKeySequence::New);  // 绑定快捷键 Ctrl+N
    newAction->setToolTip(tr("New"));
    toolBar->addAction(newAction);
    connect(newAction, &QAction::triggered,
        this, &MainWindow::onNewActionTriggered);
    // 2. 打开按钮
    QAction* openAction = new QAction(QIcon(":/icons/file_open.png"), tr("Open"), this);
    openAction->setShortcut(QKeySequence::Open);  // 绑定快捷键 Ctrl+O
    openAction->setToolTip(tr("Open"));
    toolBar->addAction(openAction);
    connect(openAction, &QAction::triggered,
        this, &MainWindow::onOpenActionTriggered);
    // 3. 保存按钮
    QAction* saveAction = new QAction(QIcon(":/icons/save.png"), tr("Save"), this);
    saveAction->setShortcut(QKeySequence::Save);  // 绑定快捷键 Ctrl+S
    saveAction->setToolTip(tr("Save"));
    connect(saveAction, &QAction::triggered,
        this, &MainWindow::onSaveActionTriggered);
    toolBar->addAction(saveAction);

    // 将工具栏添加到页面
    QVBoxLayout* layout = new QVBoxLayout(page);
    layout->addWidget(toolBar);
    layout->setContentsMargins(0, 0,0, 0);  // 移除边距
    page->setLayout(layout);

    return page;
}


QWidget* MainWindow::createHomeToolPage() {
    QWidget* page = new QWidget();
    QToolBar* toolBar = new QToolBar(page);
    toolBar->setIconSize(QSize(32, 32));

    // 第一部分：剪切板工具组
    QAction* copyAction = new QAction(QIcon(":/icons/content_copy.png"), tr("Copy"), this);
    QAction* cutAction = new QAction(QIcon(":/icons/content_cut.png"), tr("Cut"), this);
    QAction* pasteAction = new QAction(QIcon(":/icons/content_paste.png"), tr("Paste"), this);
    connect(copyAction, &QAction::triggered, m_model, &ShapeManager::copySelected);
    connect(cutAction, &QAction::triggered, m_model, &ShapeManager::cutSelected);

    toolBar->addAction(copyAction);
    toolBar->addAction(cutAction);
    toolBar->addAction(pasteAction);

    // 第二部分：文本设置
    toolBar->addSeparator();
    toolBar->addWidget(new QLabel(tr("Text")));
    // 字体下拉框
    QFontComboBox* fontCombo = new QFontComboBox();
    fontCombo->setFontFilters(QFontComboBox::ScalableFonts);
    toolBar->addWidget(fontCombo);
    // 字号下拉框
    QComboBox* fontSizeCombo = new QComboBox();
    fontSizeCombo->setEditable(true);
    for (int i = 8; i <= 72; i += 2) {
        fontSizeCombo->addItem(QString::number(i));
    }
    fontSizeCombo->setCurrentIndex(2); // 默认12号
    connect(fontCombo, &QFontComboBox::currentFontChanged, m_model, &ShapeManager::setFontFamily);
    connect(fontSizeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), m_model, &ShapeManager::setFontFontSize);
    toolBar->addWidget(fontSizeCombo);

    // 文本颜色下拉框
    QToolButton* textColorBtn = new QToolButton();
    textColorBtn->setText(tr("TextColor"));
    textColorBtn->setPopupMode(QToolButton::InstantPopup);
    QMenu* textColorMenu = createBasicColorMenu(textColorBtn);
     //连接信号处理
    connect(textColorMenu, &QMenu::triggered, [this](QAction* action) {
        if (action->data().isValid()) {
            // 处理预设颜色或透明
            QColor color = action->data().value<QColor>();
            m_model->setTextColor(color);
        }
        else {
            // 处理"颜色窗口"选项
            QColor color = QColorDialog::getColor(Qt::white, this, tr("Select Color"));
            m_model->setTextColor(color);
        }
        });
    textColorBtn->setMenu(textColorMenu);
    toolBar->addWidget(textColorBtn);

    // 第三部分：工具模式
    toolBar->addSeparator();
    QActionGroup* toolGroup = new QActionGroup(this);
    QAction* selectAction = new QAction(QIcon(":/icons/Selection.png"), tr("Select"), toolGroup);
    selectAction->setCheckable(true);//使动作可以被选中/取消
    selectAction->setChecked(true);//设置该动作为默认选中状态
    selectAction->setToolTip(tr("Select"));
    
    QAction* lineAction = new QAction(QIcon(":/icons/timeline.png"), tr("line"), toolGroup);
    lineAction->setCheckable(true);
    lineAction->setToolTip(tr("line"));
    toolBar->addAction(selectAction);
    toolBar->addAction(lineAction);
    connect(toolGroup, &QActionGroup::triggered, [this, selectAction, lineAction](QAction* action) {
        if (action == selectAction) {
            m_model->setViewState(viewState::Selection);
        }
        else if (action == lineAction) {
            m_model->setViewState(viewState::Drawline);
        }
        });

    // 第四部分：图形属性
    toolBar->addSeparator();
    toolBar->addWidget(new QLabel(tr("Shape")));

    // 填充颜色
    QToolButton* fillColorBtn = new QToolButton();
    fillColorBtn->setText(tr("fillColor"));
    fillColorBtn->setPopupMode(QToolButton::InstantPopup);//InstantPopup

    QMenu* fillColorMenu = createBasicColorMenu(fillColorBtn);
    connect(fillColorMenu, &QMenu::triggered, [this](QAction* action) {
        if (action->data().isValid()) {
            QColor color = action->data().value<QColor>();
            m_model->setFillColor(color);
        }
        else {
            // 处理"颜色窗口"选项
            QColor color = QColorDialog::getColor(Qt::white, this, tr("Select Color"));
            m_model->setFillColor(color);
        }
        });
    fillColorBtn->setMenu(fillColorMenu);
    toolBar->addWidget(fillColorBtn);

    // 线条颜色
    QToolButton* lineColorBtn = new QToolButton();
    lineColorBtn->setText(tr("lineColor"));
    lineColorBtn->setPopupMode(QToolButton::InstantPopup);
    QMenu* lineColorMenu = createBasicColorMenu(lineColorBtn);
    connect(lineColorMenu, &QMenu::triggered, [this](QAction* action) {
        if (action->data().isValid()) {
            QColor color = action->data().value<QColor>();
            m_model->setlineColor(color);
        }
        else {
            // 处理"颜色窗口"选项
            QColor color = QColorDialog::getColor(Qt::white, this, tr("Select Color"));
            m_model->setlineColor(color);
        }
        });
    lineColorBtn->setMenu(lineColorMenu);
    toolBar->addWidget(lineColorBtn);

    // 线条粗细
    // 创建一个透明的、固定宽度的 QWidget
    QWidget* spacer = new QWidget();
    spacer->setFixedWidth(10);  // 设置间距宽度
    toolBar->addWidget(spacer);
    toolBar->addWidget(new QLabel(tr("lineWidth")));
    QComboBox* lineWidthCombo = new QComboBox();
    lineWidthCombo->addItems(QStringList() << "1" << "2" << "3" << "4" << "5");
    QObject::connect(lineWidthCombo, &QComboBox::currentTextChanged,
        [this](const QString& text) {  // [this] 如果需要在 lambda 内访问类成员
            bool ok;
            int width = text.toInt(&ok);
            if (ok) {
                // 方式1：直接调用设置线宽的方法
                m_model->setlineWidth(width);  // 假设 m_model 是 ShapeManager 实例
            }
        }
    );
    toolBar->addWidget(lineWidthCombo);

    // 线条样式
    QComboBox* lineStyleCombo = new QComboBox();
    lineStyleCombo->addItem(tr("SolidLine"), static_cast<int>(Qt::SolidLine));
    lineStyleCombo->addItem(tr("DashLine"), static_cast<int>(Qt::DashLine));
    lineStyleCombo->addItem(tr("DotLine"), static_cast<int>(Qt::DotLine));
    lineStyleCombo->addItem(tr("DashDotLine"), static_cast<int>(Qt::DashDotLine));
    connect(lineStyleCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
        [this, lineStyleCombo](int index) {
            Qt::PenStyle style = static_cast<Qt::PenStyle>(lineStyleCombo->itemData(index).toInt());
            m_model->setlineStyle(style);  // 假设 m_model 有 setLineStyle 方法
        }
    );
    toolBar->addWidget(lineStyleCombo);

    QVBoxLayout* layout = new QVBoxLayout(page);
    layout->addWidget(toolBar);
    layout->setContentsMargins(0, 0, 0, 0);
    return page;
}


QWidget* MainWindow::createArrangeToolPage()
{
    QWidget* page = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(page);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    QToolBar* toolBar = new QToolBar(page);
    toolBar->setOrientation(Qt::Horizontal);
    //toolBar->setIconSize(QSize(24, 24));

    // 获取当前风格的标准图标
    QStyle* style = QApplication::style();

    // 添加上移按钮（使用箭头向上图标）
    QAction* moveUpAction = new QAction(QIcon(":/icons/arrow_circle_up.png"), tr("Up"), toolBar);
    connect(moveUpAction, &QAction::triggered, m_model, &ShapeManager::moveUp);
    toolBar->addAction(moveUpAction);

    // 添加下移按钮（使用箭头向下图标）
    QAction* moveDownAction = new QAction(QIcon(":/icons/arrow_circle_down.png"), tr("Down"), toolBar);
    connect(moveDownAction, &QAction::triggered, m_model, &ShapeManager::moveDown);
    toolBar->addAction(moveDownAction);

    // 添加置顶按钮（使用箭头向上到顶图标）
    QAction* bringToFrontAction = new QAction(QIcon(":/icons/flip_to_front.png"), tr("Top"), toolBar);
    connect(bringToFrontAction, &QAction::triggered, m_model, &ShapeManager::bringToFront);
    toolBar->addAction(bringToFrontAction);

    // 添加置底按钮（使用箭头向下到底图标)
    QAction* sendToBackAction = new QAction(QIcon(":/icons/flip_to_back.png"), tr("Bottom"), toolBar);
    connect(sendToBackAction, &QAction::triggered, m_model, &ShapeManager::sendToBack);
    toolBar->addAction(sendToBackAction);

    layout->addWidget(toolBar);
    page->setLayout(layout);

    return page;
}


QWidget* MainWindow::createPageLayoutPage() {
    QWidget* page = new QWidget();
    QToolBar* toolBar = new QToolBar(page);



    // ================= 1. 页面背景颜色下拉框 =================
    QToolButton* bgColorBtn = new QToolButton();
    bgColorBtn->setText(tr("BackgroundColor"));
    bgColorBtn->setPopupMode(QToolButton::InstantPopup);
    QMenu* bgColorrMenu = createBasicColorMenu(bgColorBtn);
    connect(bgColorrMenu, &QMenu::triggered, [this](QAction* action) {
        if (action->data().isValid()) {
            QColor color = action->data().value<QColor>();
            m_model->setPaperColor(color);
        }
        else {
            // 处理"颜色窗口"选项
            QColor color = QColorDialog::getColor(Qt::white, this, tr("Select Color"));
            m_model->setPaperColor(color);
        }
        });
    bgColorBtn->setMenu(bgColorrMenu);
    toolBar->addWidget(bgColorBtn);


    // ================= 2. 页面大小设置 =================
    QWidget* sizeContainer = new QWidget();
    QHBoxLayout* sizeLayout = new QHBoxLayout(sizeContainer);
    sizeLayout->setContentsMargins(0, 0, 0, 0);
    sizeLayout->setSpacing(4);

    // 预设尺寸下拉框
    QComboBox* sizeCombo = new QComboBox();
    sizeCombo->addItem(tr("A3 (1500px*2100px)"), QSizeF(2100, 1500));
    sizeCombo->addItem(tr("A4 (1050px*1500px)"), QSizeF(1500, 1050));
    sizeCombo->addItem(tr("A5 (750px*1050px)"), QSizeF(1050, 750));
    //sizeCombo->addItem(tr("Custom"), QSizeF());

    // 宽度/高度输入框
    QSpinBox* widthSpin = new QSpinBox();
    QSpinBox* heightSpin = new QSpinBox();
    widthSpin->setRange(10, 10000);
    heightSpin->setRange(10, 10000);
    widthSpin->setSuffix(" px");
    heightSpin->setSuffix(" px");

    // 初始化当前尺寸
    QSizeF currentSize = m_model->paperSize();
    widthSpin->setValue(currentSize.width());
    heightSpin->setValue(currentSize.height());

    // 检查当前尺寸是否匹配预设
    bool foundPreset = false;
    for (int i = 0; i < sizeCombo->count() - 1; ++i) {
        QSizeF presetSize = sizeCombo->itemData(i).toSizeF();
        if (qFuzzyCompare(presetSize.width(), currentSize.width()) &&
            qFuzzyCompare(presetSize.height(), currentSize.height())) {
            sizeCombo->setCurrentIndex(i);
            foundPreset = true;
            break;
        }
    }
    if (!foundPreset) sizeCombo->setCurrentIndex(sizeCombo->count() - 1);

    // 信号连接
    connect(sizeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        if (index < sizeCombo->count() - 1) {
            QSizeF size = sizeCombo->itemData(index).toSizeF();
            widthSpin->setValue(size.width());
            heightSpin->setValue(size.height());
            m_model->setPaperSize(size);
        }
        });

    connect(widthSpin, QOverload<int>::of(&QSpinBox::valueChanged), this, [=]() {
        m_model->setPaperSize(QSizeF(widthSpin->value(), heightSpin->value()));
        sizeCombo->setCurrentIndex(sizeCombo->count() - 1);
        });

    connect(heightSpin, QOverload<int>::of(&QSpinBox::valueChanged), this, [=]() {
        m_model->setPaperSize(QSizeF(widthSpin->value(), heightSpin->value()));
        sizeCombo->setCurrentIndex(sizeCombo->count() - 1);
        });

    sizeLayout->addWidget(sizeCombo);
    sizeLayout->addWidget(new QLabel(tr("W:")));
    sizeLayout->addWidget(widthSpin);
    sizeLayout->addWidget(new QLabel(tr("H:")));
    sizeLayout->addWidget(heightSpin);
    toolBar->addWidget(sizeContainer);

    // ================= 3. 网格开关复选框 =================
    QCheckBox* gridCheckBox = new QCheckBox(tr("Grid"));
    gridCheckBox->setChecked(m_model->showGrid());

    connect(gridCheckBox, &QCheckBox::toggled, m_model, &ShapeManager::setShowGrid);
    toolBar->addWidget(gridCheckBox);

    // ================= 整体布局 =================
    QVBoxLayout* mainLayout = new QVBoxLayout(page);
    mainLayout->setContentsMargins(0, 0, 0, 0); // 增加页面边距
    mainLayout->addWidget(toolBar);
    mainLayout->addStretch();

    return page;
}

// 辅助函数：创建颜色图标
QIcon MainWindow::createColorIcon(const QColor& color) {
    QPixmap pixmap(16, 16);
    pixmap.fill(color);
    return QIcon(pixmap);
}

QMenu* MainWindow::createBasicColorMenu(QWidget* parent)
{
    // 创建颜色菜单
    QMenu* colorMenu = new QMenu(tr("Text Color"), parent);
    // 定义6种常用颜色
    const QMap<QString, QColor> basicColors = {
        {tr("Black"), Qt::black},
        {tr("White"), Qt::white},
        {tr("Red"), Qt::red},
        {tr("Green"), Qt::green},
        {tr("Blue"), Qt::blue},
        {tr("Yellow"), Qt::yellow}
    };
    for (auto &name : basicColors.keys()) {
        QColor color = basicColors[name];
        QPixmap pix(16, 16);
        pix.fill(color);
        QAction* action = colorMenu->addAction(QIcon(pix), name);
        action->setData(color); // 存储颜色数据以便后续使用
    }
    colorMenu->addSeparator();

    // 添加透明选项
    QAction* transparentAction = new QAction(tr("Transparent"), colorMenu);
    QPixmap transparentPix(16, 16);
    transparentPix.fill(Qt::white);
    QPainter painter(&transparentPix);
    painter.fillRect(0, 0, 8, 8, Qt::lightGray);
    painter.fillRect(8, 8, 8, 8, Qt::lightGray);
    transparentAction->setIcon(QIcon(transparentPix));
    transparentAction->setData(QColor(Qt::transparent));
    colorMenu->addAction(transparentAction);

    // 4. 添加颜色窗口选项
    colorMenu->addSeparator(); // 可选的分隔线
    QAction* colorDialogAction = colorMenu->addAction(tr("More Colors..."));
    colorDialogAction->setIcon(QIcon::fromTheme(tr("color-picker"))); // 使用系统图标（可选）
    colorDialogAction->setData(QVariant()); // 标记为特殊动作

    return colorMenu;
}

//-----------文件操作--------------------------
void MainWindow::onSaveActionTriggered()
{
    std::vector<std::shared_ptr<IShape>> m_shapes = m_model->shapes();
    QString fileName = QFileDialog::getSaveFileName(
        this,
        "Save Flowchart",
        QDir::homePath(),
        "PNG Image (*.png);;SVG Vector Graphic (*.svg)"
    );

    if (fileName.isEmpty()) {
        return;
    }

    bool success = false;
    if (fileName.endsWith(".png", Qt::CaseInsensitive)) {
        success = m_model->saveToPng(m_shapes, fileName);
    }
    else if (fileName.endsWith(".svg", Qt::CaseInsensitive)) {
        // 使用新的SVGUtils保存功能
        success = SVGUtils::saveToFile(fileName, m_shapes);
    }
    else {
        fileName += ".png";
        success = m_model->saveToPng(m_shapes, fileName);
    }

    if (success) {
        QMessageBox::information(this, "Success",
            QString("File saved successfully to:\n%1").arg(fileName));

        // 可选：记录最近打开的文件
        //m_recentFiles.addRecentFile(fileName);
    }
    else {
        QMessageBox::warning(this, "Save Error",
            "Failed to save the file. Please check:\n"
            "1. File path permissions\n"
            "2. Available disk space");
    }
}

void MainWindow::onOpenActionTriggered()
{
    // 获取文件路径
    QString fileName = QFileDialog::getOpenFileName(
        this,
        "Open Flowchart",
        QDir::homePath(),
        "SVG Vector Graphic (*.svg);;All Files (*)"
    );

    if (fileName.isEmpty()) {
        return;
    }

    // 使用SVGUtils加载文件
    auto shapes = SVGUtils::loadFromFile(fileName);
    qDebug() << shapes.size();
    if (!shapes.empty()) {
        // 清空当前场景并添加新图形
        m_model->clearShapes();
        for (auto& shape : shapes) {
            m_model->addShape(shape);
        }


        // 更新窗口标题
        setWindowTitle(QString("Flowchart Editor - %1").arg(QFileInfo(fileName).fileName()));

        QMessageBox::information(this, "Success",
            QString("File loaded successfully:\n%1\n%2 shapes loaded")
            .arg(fileName)
            .arg(shapes.size()));
    }
    else {
        QMessageBox::warning(this, "Open Error",
            QString("Failed to load file:\n%1\nFile may be corrupted or unsupported")
            .arg(fileName));
    }
}

void MainWindow::onNewActionTriggered() {
    auto m_shapes = m_model->shapes();
    // 自动保存（非空时）
    if (!m_shapes.empty()) {
        QString defaultName = QString("NewDrawing-%1.graph").arg(m_autoSaveCounter++);
        SVGUtils::saveToFile(defaultName, m_shapes);  // 假设有一个 saveToFile 函数
    }

    // 清空画布
    m_model->clearShapes();
    setWindowTitle("Untitled - MyDrawingApp");
}

